package com.bfxy.lock.optimistic;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PessimisticTest2 {

    // 添加了ReentrantLock锁
    Lock lock = new ReentrantLock();

    private int i = 0;

    public static void main(String[] args) {
        PessimisticTest2 pessimisticTest2 = new PessimisticTest2();
        ExecutorService es = Executors.newFixedThreadPool(50);
        CountDownLatch cdl = new CountDownLatch(5000);
        for (int i = 0; i < 5000; i++){
            es.execute(()->{
                //修改部分  开始
                pessimisticTest2.lock.lock();
                pessimisticTest2.i++;
                pessimisticTest2.lock.unlock();
                //修改部分  结束
                cdl.countDown();
            });
        }
        es.shutdown();
        try {
            cdl.await();
            System.out.println("执行完成后，i="+ pessimisticTest2.i);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
